package com.tutu.mybatis.dynamic.datasource.config;

/**
 * @author 丘友垚
 * @version 1.0
 * @date 2020/9/23 20:29
 */
public class DynamicRoutingDataSourceHolder {

    /**
     * 主数据源key
     */
    public static final String PRIMARY_DATASOURCE = "primaryDatasource";

    /**
     * 其它数据源的前缀
     */
    public static final String KEY_PREFIX = "datasource_";

    /**
     * 数据源key缓存
     */
    private static final ThreadLocal<String> DATASOURCE_KEY = new ThreadLocal<>();

    public static void setKey(String name) {
        DATASOURCE_KEY.set(name);
    }

    public static String buildKey(Long userId) {
        return KEY_PREFIX + userId;
    }

    public static String getKey() {
        String key = DATASOURCE_KEY.get();
        if (key == null) {
            key = PRIMARY_DATASOURCE;
            setKey(key);
        }
        return key;
    }

    public static void removeKey() {
        DATASOURCE_KEY.remove();
    }
}
